package com.example.quiz.service.impl;

import com.example.quiz.dao.CategoryMapper;
import com.example.quiz.dao.QuestionMapper;
import com.example.quiz.model.Category;
import com.example.quiz.service.CategoryService;
import com.example.quiz.common.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public int add(Category category) {
        return categoryMapper.insert(category);
    }

    @Override
    @Transactional
    public int deleteById(Long id) {
        // 先检查该分类下是否有题目
        int questionCount = questionMapper.selectCountByCategoryId(id);
        if (questionCount > 0) {
            throw new BusinessException("该分类下还有" + questionCount + "道题目，不能删除");
        }
        return categoryMapper.deleteById(id);
    }

    @Override
    public int update(Category category) {
        return categoryMapper.update(category);
    }

    @Override
    @Transactional(readOnly = true)
    public Category getById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Category> getAll() {
        return categoryMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Category getByName(String categoryName) {
        // 需要在CategoryMapper中添加此方法
        return categoryMapper.selectByName(categoryName);
    }
}